package cn.uniquesoft.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import org.apache.commons.io.output.FileWriterWithEncoding;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

/**
 * @author liushuo
 * 统一处理文件工具类，包括文件是否存在
 * 文件上传等
 */
public class FileUpUtil {

    /**
     * @param path 文件路径，判断是否是目录要加上斜杠/,并且创建
     * @return
     */
    public static boolean isExistFileAndCreate(String path) {
        try {
            File file = new File(path);
            if (file.exists()) {
                return true;
            }
            String lastChar = path.trim().substring(path.trim().length());
            if (lastChar.equals(File.separator) || lastChar.equals("/") || lastChar.equals("\\")) {
                file.mkdirs();
                return true;
            } else {
                lastChar = path.trim().substring(0, path.trim().lastIndexOf(File.separator) + 1);
                File mfile = new File(lastChar);
                if (!mfile.exists()) {
                    mfile.mkdirs();
                }
                file.createNewFile();
                return true;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 上传文件到指定的path，采用输入输出流方式
     *
     * @param path
     * @param file
     * @return
     */
    public static String fileUpload(String path, MultipartFile file) {
        try {
            OutputStream out = new FileOutputStream(new File(path));
            InputStream is = null;
            is = file.getInputStream();

            byte[] b = new byte[1024];
            while (is.read(b) != -1) {
                out.write(b);
            }
            out.flush();
            out.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        return null;
    }


    private static String htmlTailStr = "\r\n";

    /**
     * @param filepath     存放路径
     * @param tableRemarks 标题名称
     * @param fileName     文件名称
     * @param content      文件内容
     * @return
     */
    public static String parseHtml(String filepath, String tableRemarks, String fileName, String content) {

        StringBuffer sb = new StringBuffer();
        sb.append("<!DOCTYPE html>" + htmlTailStr);
        sb.append("<html>" + htmlTailStr);
        sb.append("<head>" + htmlTailStr);
        sb.append("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\" />" + htmlTailStr);
        sb.append("<title>" + tableRemarks + "</title>" + htmlTailStr);
        // sb.append("<meta name=\"viewport\" content=\"width=device-width,
        // initial-scale=1.0\" />" + htmlTailStr);
        sb.append("<style type='text/css'>iframe{width:100%;height:200px;}</style>");
        sb.append("<script type='text/javascript'>" + htmlTailStr +
                "window.onload = window.onresize = function () {"
                + "resizeIframe();}" + htmlTailStr + "var resizeIframe=function(){" + htmlTailStr
                + "var bodyw=document.body.clientWidth;" + htmlTailStr
                + "for(var ilength=0;ilength<=document.getElementsByTagName(\"iframe\").length;ilength++){" + htmlTailStr
                + "document.getElementsByTagName(\"iframe\")[ilength].height = bodyw*9/16;" + htmlTailStr + "}}" + htmlTailStr
                + "</script>");

        sb.append("</head>" + htmlTailStr);
        sb.append("<body class=\"inside-header inside-aside \">" + htmlTailStr);
        sb.append(content);
        sb.append("</body></html>" + htmlTailStr);

        FileUpUtil.writeFile(filepath, fileName, sb.toString());
        return sb.toString();
    }

    public static void writeFile(String filePath, String fileName, String content) {
        String dir = filePath;
        String fn = dir + "/" + fileName;
        // System.out.println("dir:" + dir);
        try {
            File file = new File(dir);
            if (!file.exists()) {
                file.mkdirs();
            }
            file = new File(file, fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriterWithEncoding fw = new FileWriterWithEncoding(fn, "UTF-8");
            PrintWriter pw = new PrintWriter(fw);
            pw.println(content);
            pw.flush();
            pw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static String convertFileSize(long size) {
        long kb = 1024;
        long mb = kb * 1024;
        long gb = mb * 1024;

        if (size >= gb) {
            return String.format("%.1f GB", (float) size / gb);
        } else if (size >= mb) {
            float f = (float) size / mb;
            return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f);
        } else if (size >= kb) {
            float f = (float) size / kb;
            return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f);
        } else
            return String.format("%d B", size);
    }

    /**
     * @author wty
     * @DESCRIPTION:
     * @params: [base64 图片base64字符串, filePath 文件路径 files/visit ]
     * @return: String 文件名
     * @Date: 2019/1/15 13:21
     * @Modified By:
     */
    public static String base64Upload(String base64, String filePath) throws Exception {
        // 通过base64来转化图片
        base64 = base64.replaceAll("data:image/jpeg;base64,", "").replaceAll("_", "+");
        BASE64Decoder decoder = new BASE64Decoder();
        // Base64解码
        byte[] imageByte = decoder.decodeBuffer(base64);
        for (int i = 0; i < imageByte.length; ++i) {
            // 调整异常数据
            if (imageByte[i] < 0) {
                imageByte[i] += 256;
            }
        }
        // 生成文件名
        String files = new SimpleDateFormat("yyyyMMddHHmmssSSS")
                .format(new Date())
                + (new Random().nextInt(9000) % (9000 - 1000 + 1) + 1000)
                + ".jpg";
        // 生成文件路径
        filePath = ContextUtil.getRequest().getSession().getServletContext().getRealPath("/") + filePath;
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        String filename = filePath + File.separator + files;
        OutputStream imageStream = new FileOutputStream(filename);
        imageStream.write(imageByte);
        imageStream.flush();
        imageStream.close();

        return files;
    }
}
